<template>
  <!-- 集采汇总编辑页 -->
  <div class="e-form">
    <div class="tabs" v-if="Object.keys(basicFormData).length != 0" warningTabs>
      <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
        <!-- 基本信息 -->
        <el-tab-pane
          label="基本信息"
          name="baseInfo"
          :disabled="clickTabFlag"
        ></el-tab-pane>
        <el-tab-pane
          label="汇总明细"
          name="planDetail"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <el-tab-pane
          label="附件信息"
          name="accessory"
          :disabled="clickTabFlag"
        ></el-tab-pane>
        <el-tab-pane
          label="审核历史"
          name="auditHistory"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <div>
          <!-- 基本信息 -->
          <div id="baseInfoCon" class="con">
            <div class="e-form">
              <BillTop title="集采汇总编辑" @cancel="handleClose"></BillTop>
              <div class="tabs">
                <div class="tabs-title" id="baseInfo">基本信息</div>
                <div style="width: 100%" class="form">
                  <el-form
                    :model="basicFormData"
                    ref="ruleForm"
                    :rules="rules"
                    class="demo-ruleForm"
                  >
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="汇总编号">
                          {{ basicFormData.billNo }}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="单据机构">
                          {{ basicFormData.orgName }}
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="计划金额(元)">
                          <!-- 汇总所选择申报机构对应清单的人民币金额。保留两位小数  明细里的 金额（元）-->
                          {{basicFormData.amount}}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="汇总日期">
                          <el-date-picker
                            v-model="basicFormData.summaryDate"
                            type="date"
                            placeholder="选择日期"
                            value-format="yyyy-MM-dd"
                            :clearable="false"
                          >
                          </el-date-picker>
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="操作人">
                          {{ basicFormData.operator }}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="状态">
                          <span>{{
                            ["草稿", "审核中", "已审核", "已关闭",'', "已作废"][
                              basicFormData.state
                            ]
                          }}</span>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-form-item label="备注">
                        <el-input
                          type="textarea"
                          :rows="2"
                          placeholder="请输入内容"
                          v-model="basicFormData.remarks"
                        >
                        </el-input>
                      </el-form-item>
                    </el-row>
                  </el-form>
                </div>
              </div>
            </div>
          </div>

          <!-- 汇总明细 -->
          <div id="planDetailCon" class="con">
            <div class="tabs-title" id="planDetail">汇总明细</div>
            <el-tabs
              :class="'childTab ' + childTabClass"
              tab-position="left"
              v-model="tabsNameChild"
              @tab-click="onChangeTab"
            >
              <el-tab-pane
                label="按申报机构汇总"
                name="materialDetails"
                :disabled="clickTabFlag"
              ></el-tab-pane>
              <el-tab-pane
                label="物资汇总"
                name="technicalParameter"
                :disabled="clickTabFlag"
              ></el-tab-pane>
              <div>
                <div id="planDetailCon">
                  <div class="tabs-title" id="materialDetails">
                    按申报机构汇总
                  </div>
                  <div class="e-table">
                    <div class="top">
                      <div class="left">
                        <div>
                          <el-button
                            size="small"
                            style="background: rgb(75, 178, 255); color: #fff"
                            @click="selectUnit"
                             class="btn-blue"
                            >选择申报单位</el-button
                          >

                          <el-button
                            size="small"
                            type="danger"
                            @click="deleteMaterials"
                             class="btn-delete"
                            >删除</el-button
                          >
                        </div>
                      </div>
                    </div>

                  <!-- 申报机构选择 -->
                    <el-table
                    class="table"
                      :data="OrgtableData"
                      border
                      style="width: 100%"
                      :row-class-name="tableRowClassName"
                      @cell-mouse-enter="cellMouseEnter"
                      @cell-mouse-leave="cellMouseLeave"
                      :cell-class-name="cellClsNm"
                      :header-cell-style="{ textAlign: 'center' }"
                      :cell-style="{ textAlign: 'center' }"
                      @selection-change="planTableSelect"
                       ref="table"
                v-sortTable="{ 'tableData': OrgtableData, '_this': this, 'ref': 'table' }"
                    >
                      <el-table-column type="selection" width="55">
                      </el-table-column>
                      <el-table-column
                        prop="masterPlanBillNo"
                        label="总计划编号"
                        min-width="300"
                      >
                        <template slot-scope="scope">
                          <span
                            @click="showTable(scope.row)"
                            style="color: blue; cursor: pointer"
                          >
                            {{ scope.row.masterPlanBillNo }}
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="orgName"
                        label="机构名称"
                        min-width="300"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="amount"
                        label="金额(元)"
                        width="200"
                      >
                      </el-table-column>
                    </el-table>
                  <!-- 子列表 -->

                    <div  v-if="show" style=" margin-top: 20px;">
                        <div class="top">
                      <div class="left">
                        <div>
                          <el-button
                            size="small"
                            style="background: rgb(75, 178, 255); color: #fff"
                            @click="selectPlans"
                             class="btn-blue"
                            >选择计划明细</el-button
                          >
                        </div>
                      </div>
                    </div>
                    <div class="errorMsg" v-if="errorMsg.length > 0">
                            <span v-for="(item, index) in errorMsg" :key="index">
                            {{ item }}
                            </span>
                        </div>
                        <el-table
                        class="table"
                          :data="OrgSonTableData"
                          border
                          style="width: 100%; margin-top: 20px"
                          :row-class-name="tableRowClassNames"
                          @cell-mouse-enter="cellMouseEnter"
                          @cell-mouse-leave="cellMouseLeave"
                          :cell-class-name="cellClsNm"
                          :header-cell-style="{ textAlign: 'center' }"
                          :cell-style="{ textAlign: 'center' }"
                          @selection-change="planTableSelect"
                          :tree-props="{
                              children: 'children',
                              hasChildren: 'hasChildren',
                            }"
                          row-key="uuid"
                          :max-height="$store.state.tableHeight"
                           ref="table"
                v-sortTable="{ 'tableData': OrgSonTableData, '_this': this, 'ref': 'table' }"
                        >
                          <el-table-column
                            label="操作"
                            fixed
                            width="100px"
                            align="left"
                          >
                            <template slot-scope="{ row ,$index}">
                              <i
                                class="el-icon-delete"
                                style="cursor: pointer; font-size: 20px"
                                :class="{
                                  'icon-delete-active-color':
                                    MouseEnterId == row.dtlId,
                                }"
                                @click="deleteEle(row)"
                                v-if="$index > 0"
                              ></i>
                            </template>
                          </el-table-column>
                          <el-table-column
                            prop="materialClassName"
                            label="物资类别"
                            min-width="150"
                          >
                          </el-table-column>
                          <el-table-column
                            prop="materialName"
                            label="物资名称"
                            min-width="150"
                          >
                          </el-table-column>
                          <el-table-column prop="spec" label="规格型号" width="100">
                          </el-table-column>
                          <el-table-column prop="unit" label="计量单位" width="100">
                          </el-table-column>
                          <el-table-column
                            prop="texture"
                            label="材质"
                            min-width="150"
                          >
                          </el-table-column>
                          <el-table-column
                            prop="planQuantity"
                            label="计划数量"
                            min-width="150"
                          >
                          </el-table-column>
                          <el-table-column
                            prop="authorizedQuantity"
                            label="核准数量"
                            width="110"
                          >
                          <!-- 默认值带入待汇总剩余计划数量，可修改，不能超过剩余计划数量。 -->
                            <template slot-scope="{ row,$index }">
                              <el-input
                                v-enter-float="{
                                        set: row,
                                        key: 'authorizedQuantity'
                                    }"
                              @blur="blur"
                                @input="input(row)"
                                v-model="row.authorizedQuantity"
                                clearable
                                v-if="$index > 0"
                              ></el-input>
                            </template>
                          </el-table-column>
                          <el-table-column
                            prop="authorizedPrice"
                            label="核准单价（元）"
                            width="130"
                          >
                          <!-- 默认同市场单价，可修改 -->
                            <template slot-scope="{ row,$index  }">
                              <el-input
                                v-enter-float="{
                                        set: row,
                                        key: 'authorizedPrice'
                                    }"
                              @blur="blur"
                                @input="input(row)"
                                v-model="row.authorizedPrice"
                                  v-if="$index > 0"
                                clearable
                              ></el-input>
                            </template>
                          </el-table-column>
                          <el-table-column
                            prop="marketPrice"
                            label="市场单价（元）"
                            width="130"
                          >
                          </el-table-column>
                          <el-table-column
                            prop="amount"
                            label="金额（元）"
                            width="130"
                          >
                          <!-- 系统默认计算，即核准数量*核准单价，不可编辑，保留2位小数，采用四舍五入方式。 -->
                          </el-table-column>
                          <el-table-column
                            prop="purchasingUnitName"
                            width="150"
                          >
                          <!-- 录入人可选择，审核中也可由审核人核准数据为准，单选，弹窗选择全集团组织机构数据，支持批量选择。 -->
                           <template  slot="header">
                             <span>集中采购单位</span>
                             <i slot="suffix" class="el-input__icon el-icon-document-copy" style=" cursor: pointer;" @click="selectPurchasingUnitName()"></i>
                            </template>
                              <template slot-scope="{ row,$index  }">
                              <el-input
                                @input="input(row)"
                                v-model="row.purchasingUnitName"
                                  v-if="$index > 0"
                              >
                              <i slot="suffix" class="el-input__icon el-icon-document-copy" style=" cursor: pointer;" @click="selectPurchasingUnitNames(row)"></i>
                              </el-input>
                            </template>
                          </el-table-column>
                          <el-table-column
                            prop="procurementMethod"
                            label="采购方式"
                            width="150"
                          >
                           <template  slot="header">
                            <span>采购方式</span>
                            <i slot="采购方式" class="el-input__icon el-icon-document-copy" style=" cursor: pointer;" @click="selectPurchaseType()"></i>
                            </template>
                            <template slot-scope="{ row,$index  }">
                              <el-select v-model="row.procurementMethod" placeholder="请选择" v-if="$index > 0" @change="selectProcurementMethod(row)">
                                  <el-option
                                    v-for="item in procurementMethod"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                  </el-option>
                            </el-select>
                            </template>
                          <!-- 录入人可选择，审核中由审核人可修改，下拉单选，支出批量选择。包括：
                              如果选择“业主招标”，那么项目部不需要走招标流程，可直接引用这类物资签订合同。指定的“采购单位”作为可引用项目部的设定值，可以直接引用 -->
                          </el-table-column>
                          <el-table-column
                            prop="contractorName"
                            label="承建单位"
                            width="100"
                          >
                          <!-- 默认读取申报机构的上级承建单位数据 -->
                          </el-table-column>
                          <el-table-column
                            prop="remarks"
                            label="备注"
                            width="100"
                          >
                          <!-- 审核中，由当前审核人可填写 -->
                          </el-table-column>
                        </el-table>

                    </div>

                  </div>
                </div>
              <!--  物资汇总   -->
                <div id="planDetailCon">
                  <div class="tabs-title" id="technicalParameter">物资汇总</div>
                  <div class="e-table">
                    <!-- 汇总所有物资 -->
                     <div class="errorMsg" v-if="errorMsg.length > 0">
                        <span v-for="(item, index) in errorMsg" :key="index">
                        {{ item }}
                        </span>
                    </div>
                    <el-table
                    class="table"
                      :data="materialsTableData"
                      border
                      style="width: 100%"
                      :row-class-name="tableRowClassNamess"
                      @cell-mouse-enter="cellMouseEnter"
                      @cell-mouse-leave="cellMouseLeave"
                      :cell-class-name="cellClsNm"
                      :header-cell-style="{ textAlign: 'center' }"
                      :cell-style="{ textAlign: 'center' }"
                      :tree-props="{
                            children: 'children',
                            hasChildren: 'hasChildren',
                             }"
                       row-key="uuid"
                       :max-height="$store.state.tableHeight"
                        ref="table"
                v-sortTable="{ 'tableData': materialsTableData, '_this': this, 'ref': 'table' }"
                    >
                      <el-table-column prop="materialClassName" label="物资类别" width="200">
                      </el-table-column>
                      <el-table-column
                        prop="materialName"
                        label="物资名称"
                        min-width="200"
                      >
                      <template slot-scope="scope">
                          <span
                            @click="showA(scope.row)"
                            style="color: blue; cursor: pointer"
                          >
                            {{ scope.row.materialName }}
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="spec" label="规格型号" width="100">
                      </el-table-column>
                      <el-table-column prop="unit" label="计量单位" width="100">
                      </el-table-column>
                      <el-table-column prop="texture" label="材质" width="100">
                      </el-table-column>
                      <el-table-column prop="planQuantity" label="计划数量" width="100">
                      </el-table-column>
                      <el-table-column prop="amount" label="金额（元）" width="100">
                      </el-table-column>
                      <el-table-column prop="procurementMethod" label="采购方式" width="150">
                           <template slot-scope="{ row,$index  }">
                              <el-select v-model="row.procurementMethod" placeholder="请选择" v-if="$index > 0" @change="selectProcurementMethodTwo(row)">
                                  <el-option
                                    v-for="item in procurementMethod"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                  </el-option>
                            </el-select>
                            </template>
                      </el-table-column>
                       <el-table-column prop="purchasingUnitName"  width="170">
                             <template  slot="header">
                             <span>集中采购单位</span>
                             <i slot="suffix" class="el-input__icon el-icon-document-copy" style=" cursor: pointer;" @click="materialsSelectPurchasingUnitName()"></i>
                            </template>
                              <template slot-scope="{ row,$index  }">
                              <el-input
                                @input="input(row)"
                                v-model="row.purchasingUnitName"
                                  v-if="$index > 0"
                              >
                              <i slot="suffix" class="el-input__icon el-icon-document-copy" style=" cursor: pointer;" @click="materialsTableSelectPurchasingUnitName(row)"></i>
                              </el-input>
                            </template>
                      </el-table-column>

                       <!-- <el-table-column prop="marketPrice" label="市场单价（元）" width="120">
                      </el-table-column>
                      <el-table-column prop="budgetAmount" label="金额（元）" width="100">
                      </el-table-column> -->

                    </el-table>

                    <!-- 机构汇总表 -->
                   <el-table
                   class="table"
                      :data="materialsNameData"
                      border
                      style="width: 100%; margin-top: 20px"
                      @cell-mouse-enter="cellMouseEnter"
                      @cell-mouse-leave="cellMouseLeave"
                      :cell-class-name="cellClsNm"
                      :header-cell-style="{ textAlign: 'center' }"
                      :cell-style="{ textAlign: 'center' }"
                      v-if="showTwo"
                      :tree-props="{
                            children: 'children',
                            hasChildren: 'hasChildren',
                             }"
                       row-key="uuid"
                       :max-height="$store.state.tableHeight"
                        ref="table"
                v-sortTable="{ 'tableData': materialsNameData, '_this': this, 'ref': 'table' }"
                    >
                      <el-table-column prop="orgName" label="机构名称" min-width="200">
                      </el-table-column>
                      <el-table-column
                        prop="materialName"
                        label="物资名称"
                        min-width="100"
                      >
                      </el-table-column>
                      <el-table-column prop="spec" label="规格型号" width="100">
                      </el-table-column>
                      <el-table-column prop="unit" label="计量单位" width="100">
                      </el-table-column>
                      <el-table-column prop="texture" label="材质" width="100">
                      </el-table-column>
                      <el-table-column prop="planQuantity" label="计划数量" width="100">
                      </el-table-column>
                       <el-table-column prop="planQuantity" label="市场单价（元）" width="100">
                      </el-table-column>
                      <el-table-column prop="amount" label="金额（元）" width="100">
                      </el-table-column>

                    </el-table>

                  </div>
                </div>
              </div>
            </el-tabs>
          </div>

          <!-- 附件信息 -->
          <div id="accessoryCon" class="con">
            <div class="tabs-title" id="accessory">附件信息</div>
            <attach-comp
              :relationId="attachId"
              bucketName="material"
              v-if="objFlag.flag5 && basicFormData.state==0 || basicFormData.state==1"
            />
            <attach-comp
              :relationId="attachId"
              bucketName="material"
              v-else-if="objFlag.flag5 && basicFormData.state == 2 || basicFormData.state == 5"
              isView
            />

            <div class="seize-a-seat" v-else>
              <i class="el-icon-loading"></i>
            </div>
          </div>
          <!-- 审核历史 -->
            <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                :tableData.sync="auditHistoryTable"
                                @getAuditHistory="getAuditHistory"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>
        </div>
      </el-tabs>
    </div>
    <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
    <div class="buttons">
      <span class="tip"
        ><span style="color: red; margin-right: 0">*</span>为必填项</span
      >
       <el-button
          type="primary"
          style="background: #2e61d7"
          v-debounce
          v-if="basicFormData.state === '1'"
          >打印</el-button
      >
      <ComExaButtons
        v-if="basicFormData.state != 5"
        :auditState="auditState"
        :state="basicFormData.state"
            :founderId="founderId"
        @exas="exas"
    />
      <!-- <el-button
        type="primary"
        size="small"
        style="background: #2e61d7"
        v-debounce
        @click="save()"
        >保存</el-button
      >
      <el-button
        type="primary"
        size="small"
        style="background: #2e61d7"
        @click="submit()"
        v-debounce
        >保存并提交</el-button
      >
       <el-button
        type="primary"
        size="small"
        style="background: #2e61d7"
        v-if="basicFormData.state === '1'"
        @click="undoAudit"
        v-debounce
        >撤回</el-button
      >
      <el-button
        type="primary"
        class="btn-delete"
        v-debounce
        v-if="basicFormData.state === '1'"
        @click="nullify()"
        >作废</el-button
          >
      <el-button
        type="danger"
        size="small"
       class="btn-delete"
        @click="ctDelete"
        v-if="basicFormData.state === '0'"
        v-debounce
        >删除</el-button
      > -->
      <el-button size="small" @click="handleClose">关闭</el-button>
    </div>
  </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations, mapState } from 'vuex'
import {  getUuid, selectDataClient, openAppClient } from '@/utils/common'
import AttachComp from '@/components/common/attachIndex'
import Api from '@/api/materials/purchaseCollect.js'
import CommonApi from '@/api/materials/common.js'
import ComAuditHistoryIndex from '@/pages/materialsmanagement/components/auditHistory/auditHistoryIndex'
export default {
    data () {
        return {
            tabsName: 'baseInfo',
            userName: '',
            clickId: 'baseInfo',
            tabsNameChild: '',
            childTabClass: '',
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: '',
            },
            procurementMethod: [{
                value: 0,
                label: '邀请招标'
            }, {
                value: 1,
                label: '公开招标'
            }, {
                value: 2,
                label: '询价'
            }, {
                value: 3,
                label: '竞争性谈判'
            }, {
                value: 4,
                label: '单一性来源'
            },
            {
                value: 5,
                label: '甲控（业主招标）'
            }],
            auditState: {}, //按钮状态
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [],
            isErrorMsg: true, //是否提醒错误信息
            OrgtableData: [], //申报机构数据
            OrgSonTableData: [], //申报机构子列表
            materialsTableData: [], //物资汇总数据
            materialsNameData: [], //物资名称汇总机构
            auditHistoryTable: [], //审核历史
            planSelect: [], //申报机构表格明细选择项
            value: '',
            textarea: '',
            formData: {},
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            MouseEnterId: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            basicFormData: {
                'amount': null,
                'billId': '',
                'billNo': '',
                'founderId': '',
                'founderName': '',
                'gmtCreate': '',
                'gmtModified': '',
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': '',
                'operator': '',
                'operatorId': '',
                'orgId': '',
                'orgName': '',
                'remarks': '',
                'sourceBillId': '',
                'sourceBillNo': '',
                'sourceType': null,
                'state': '',
                'summaryDate': '',
                'workId': ''
            },
            objFlag: {
                flag5: false,
            },
            orgId: '', //机构id
            orgName: '', //机构名称
            billid: '',
            isSkip: false, //是否跳转
            show: true, //申报机构子列表
            showTwo: false,
            dtlIds: '', //
            billIdArr: [],
            OrgAllData: [],
            masterPlanBillId: '',
            data: [],
            resss: {},
            //验证
            rules: {
                summaryDate: [
                    {
                        required: true,
                        message: '请输入汇总日期',
                        trigger: 'blur',
                    },
                ],

            },
            auditParams: {
                billId: this.$route.query.billid, //单据Id  ***
                billType: '1004', //单据编码  ***
                dtls: [], //审核中字段值变更历史
                freeNextUnitIndex: 0, //下一步审核步骤
                freeNextUser: '', //下一步审核人ID
                isPass: true, //审核是否通过
                isShareInAudit: true, //是否共享审核节点
                opinion: '', //审核意见   ***
                orgId: JSON.parse(localStorage.getItem('vuex')).userInfo.orgInfo.orgId, //单据机构Id
                orgName: JSON.parse(localStorage.getItem('vuex')).userInfo.orgInfo.orgName, //单据机构名称
                userId: localStorage.getItem('userId'), //审核人Id    ***
                workId: '', //流程Id
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 1004,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': ''
            },

        }
    },
    created () {
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.orgId = data.userInfo.orgInfo.orgId
        this.orgName = data.userInfo.orgInfo.orgName
        this.userId = localStorage.getItem('userId')
        this.basicFormData.operator = localStorage.getItem('userName')
        this.billid = this.$route.query.billid
        this.founderId = localStorage.getItem('userId')
        this.getBasicData() //进入页面就获取基本信息数据
        this.getAttach()
        this.getMasterPurchase() //获取明细
        // this.isdata()
        this.getSettingListById() //获取明细物资汇总
        this.getCurrentUnitInfo()

    },
    methods: {
        ...mapMutations(['setSelectedInfo', 'setAuditParams']),
        // 获取按钮状态
        getCurrentUnitInfo () {
            CommonApi
                .getCurrentUnitInfo({
                    billId: this.$route.query.billid,
                    billType: 1004,
                    freeNextUnitIndex: 0,
                    freeNextUser: '',
                    isPass: true,
                    isShareInAudit: true,
                    opinion: ''
                })
                .then(res => {
                    this.auditState = res
                })
        },
        // 按钮组件触发事件
        exas (data) {
            switch (data) {
            case 'audit':
                this.audit() //审核
                break
            case 'undoAudit':
                this.undoAudit() //撤回
                break
            case 'submitCommit':
                this.submit() //提交
                break
            case 'submit':
                this.save() //保存
                break
            case 'nullify':
                this.nullify() //作废
                break
            case 'deleteData':
                this.ctDelete() //删除
                break
            default:
                break
            }
        },
        //作废
        nullify () {
            this.setAuditParams(this.nullifyParams)
            openAppClient('/nullifyDialog', '单据作废原因', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                CommonApi.nullify(auditParams).then(() => {
                    this.clientPop('suc', '作废成功', this.handleClose, null, this.handleClose)
                })
            })
        },
        //跳转到明细
        scorllDtl () {
            if(this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        //选择采购方式  批量
        selectPurchaseType () {

            let ids = []
            selectDataClient({
                SelectServiceToken: '/config/kv/getDicValue', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: JSON.stringify({
                    type: 1,
                    dicName: '总计划明细采购方式',
                    dicKey: '',
                }),
                Title: '选择采购方式' // 标题
            })
                .then(val=>{
                    this.setSelectedInfo(val)

                    // let val = [{ 'dicId': '1530100054226894848', 'kvId': '1530100326869237760', 'kvKey': '询价', 'kvValue': '2', 'kvStatus': 1, 'kvDescription': '询价' }]
                    val.forEach(b=>{

                        this.OrgSonTableData.forEach(item=>{

                            item.children.forEach(a=>{
                                if(a.changeType === 1) {
                                    a.changeType = 1
                                    item.changeType = 1
                                }else{
                                    a.changeType = 2
                                    item.changeType = 2

                                }
                                a.procurementMethod = b.kvValue
                                if(a.procurementMethod == 0) {
                                    a.procurementMethod = '邀请招标'
                                }else if(a.procurementMethod == 1) {
                                    a.procurementMethod = '公开招标'
                                }else if(a.procurementMethod == 2) {
                                    a.procurementMethod = '询价'
                                }else if(a.procurementMethod == 3) {
                                    a.procurementMethod = '竞争性谈判'
                                }else if(a.procurementMethod == 4) {
                                    a.procurementMethod = '单一性来源'
                                }else if(a.procurementMethod == 5) {
                                    a.procurementMethod = '甲控（业主招标）'
                                }
                                this.materialsTableData.forEach(k=>{
                                    k.children.forEach(v=>{
                                        if(v.changeType == 1) {
                                            if(v.materialId == a.materialId)  {
                                                v.changeType = 1
                                                v.procurementMethod = a.procurementMethod
                                            }
                                        }else if(v.changeType == 2 || v.changeType == null || v.changeType == 0) {
                                            if(v.materialId == a.materialId)  {
                                                v.changeType = 2
                                                v.procurementMethod = a.procurementMethod
                                            }
                                        }
                                    })
                                })
                                this.OrgtableData.forEach(o=>{
                                    o.children.forEach(j=>{
                                        j.children.forEach(l=>{

                                            if(l.changeType == 1) {
                                                l.changeType = 1
                                                l.procurementMethod = a.procurementMethod
                                            }  else if(l.changeType == 2 || l.changeType == null || l.changeType == 0) {
                                                l.changeType = 2
                                                l.procurementMethod =  a.procurementMethod
                                            }

                                        })
                                    })
                                })
                            })
                        })

                    })
                })

        },
        //转换采购方式的格式
        isprocurementMethod () {
            this.OrgSonTableData.forEach(a=>{
                a.children.forEach(c=>{
                    if(c.procurementMethod == '邀请招标') {
                        c.procurementMethod = 0
                    }else if(c.procurementMethod == '公开招标') {
                        c.procurementMethod = 1
                    }else if(c.procurementMethod == '询价') {
                        c.procurementMethod = 2
                    }else if(c.procurementMethod == '竞争性谈判') {
                        c.procurementMethod = 3
                    }else if(c.procurementMethod == '单一性来源') {
                        c.procurementMethod = 4
                    }else if(c.procurementMethod == '甲控（业主招标）') {
                        c.procurementMethod = 5
                    }
                })

            })
            this.materialsTableData.forEach(a=>{
                a.children.forEach(c=>{
                    if(c.procurementMethod == '邀请招标') {
                        c.procurementMethod = 0
                    }else if(c.procurementMethod == '公开招标') {
                        c.procurementMethod = 1
                    }else if(c.procurementMethod == '询价') {
                        c.procurementMethod = 2
                    }else if(c.procurementMethod == '竞争性谈判') {
                        c.procurementMethod = 3
                    }else if(c.procurementMethod == '单一性来源') {
                        c.procurementMethod = 4
                    }else if(c.procurementMethod == '甲控（业主招标）') {
                        c.procurementMethod = 5
                    }
                })
            })
        },
        //申报机构选择集中采购单位  批量选择
        selectPurchasingUnitName () {
            let ids = []
            selectDataClient({
                SelectServiceToken: '/hr/org/getAllOrgPage', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                Title: '选择机构' // 标题
            })
                .then(val=>{
                    this.setSelectedInfo(val)
                    // openAppClient('/showSelectedData', '选择结果', function () {
                    //     // alert('关闭后回调')
                    // })
                    // let val = [{ 'orgId': '1439990096949411840', 'orgName': '贵州江习古高速公路开发有限公司', 'shortCode': 'JSGS', 'orgType': '2', 'parentId': '1439990097591140354', 'parentName': '四川路桥建设集团股份有限公司' }]
                    val.forEach(item=>{
                        this.OrgtableData.forEach(a=>{
                            if(a.changeType === 1) {
                                a.changeType = 1
                            }else{
                                a.changeType = 2
                            }
                            a.children.forEach(b=>{
                                b.children.forEach(c=>{
                                    if(c.changeType === 1) {
                                        c.purchasingUnitId = item.orgId
                                        c.purchasingUnitName = item.orgName
                                        c.changeType = 1
                                    }else{

                                        c.purchasingUnitId = item.orgId
                                        c.purchasingUnitName = item.orgName
                                        c.changeType = 2
                                    }
                                })
                            })
                        })
                    })
                    val.forEach(item=>{
                        this.OrgSonTableData.forEach(a=>{
                            a.children.forEach(b=>{
                                b.purchasingUnitId = item.orgId
                                b.purchasingUnitName = item.orgName

                                this.materialsTableData.forEach(c=>{
                                    c.children.forEach(v=>{
                                        if(b.materialId == v.materialId) {
                                            v.purchasingUnitId = item.orgId
                                            v.purchasingUnitName = item.orgName
                                            if(v.changeType == 1) {
                                                v.changeType = 1
                                            }else if(v.changeType == 2) {
                                                v.changeType = 2
                                            }else if(v.changeType == 0 || v.changeType == null) {
                                                v.changeType =  0
                                            }
                                        }
                                    })
                                })
                            })
                        })
                    })
                })

        },
        //申报机构选择集中采购单位  单个选择
        selectPurchasingUnitNames (row) {
            // console.log('row', row)
            let ids = []
            selectDataClient({
                SelectServiceToken: '/hr/org/getAllOrgPage', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                Title: '选择机构' // 标题
            })
                .then(val=>{
                    this.setSelectedInfo(val)
                    // let val = [{ 'orgId': '1439990096949411840', 'orgName': '四川高速公路开发有限公司', 'shortCode': 'JSGS', 'orgType': '2', 'parentId': '1439990097591140354', 'parentName': '四川路桥建设集团股份有限公司' }]
                    val.forEach(item=>{
                        row.purchasingUnitId = item.orgId
                        row.purchasingUnitName = item.orgName
                        row.changeType = 2
                        this.OrgSonTableData.forEach(a=>{
                            a.children.forEach(b=>{
                                if(b.dtlId) {
                                    row.changeType = 2
                                    this.materialsTableData.forEach(c=>{
                                        c.children.forEach(v=>{
                                            if(v.materialId === row.materialId) {
                                                v.purchasingUnitId = item.orgId
                                                v.purchasingUnitName = item.orgName
                                                v.changeType = 2
                                            }
                                        })
                                    })
                                }else{
                                    row.changeType = 1
                                    this.materialsTableData.forEach(c=>{
                                        c.children.forEach(v=>{
                                            if(v.materialId === row.materialId) {
                                                v.purchasingUnitId = item.orgId
                                                v.purchasingUnitName = item.orgName
                                                v.changeType = 1
                                            }
                                        })
                                    })
                                }
                            })
                        })

                    })
                })

        },
        //物资汇总选择集中采购单位  //批量选择
        materialsSelectPurchasingUnitName (row) {
            console.log('row', row)
            let ids = []
            selectDataClient({
                SelectServiceToken: '/hr/org/getAllOrgPage', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                Title: '选择机构' // 标题
            })
                .then(val=>{
                    this.setSelectedInfo(val)
                    val.forEach(item=>{
                        this.materialsTableData.forEach(a=>{
                            a.children.forEach(b=>{
                                if(b.changeType === 1) {
                                    b.changeType = 1
                                    b.purchasingUnitId = item.orgId
                                    b.purchasingUnitName = item.orgName
                                }else {
                                    b.changeType = 2
                                    b.purchasingUnitId = item.orgId
                                    b.purchasingUnitName = item.orgName
                                }
                                this.OrgSonTableData.forEach(c=>{
                                    c.children.forEach(v=>{
                                        if(b.materialId == v.materialId) {
                                            v.purchasingUnitId = item.orgId
                                            v.purchasingUnitName = item.orgName
                                            v.changeType = 2
                                        }
                                    })
                                })
                            })
                        })
                    })

                })

        },
        //物资汇总选择集中采购单位  //单个选择
        materialsTableSelectPurchasingUnitName (row) {
            console.log('row', row)
            let ids = []
            selectDataClient({
                SelectServiceToken: '/hr/org/getAllOrgPage', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                Title: '选择机构' // 标题
            })
                .then(val=>{
                    this.setSelectedInfo(val)
                    val.forEach(item=>{
                        row.purchasingUnitId = item.orgId
                        row.purchasingUnitName = item.orgName
                        row.changeType = 2
                        this.OrgSonTableData.forEach(a=>{
                            a.children.forEach(b=>{
                                if(b.dtlId) {
                                    row.changeType = 2
                                    this.OrgSonTableData.forEach(c=>{
                                        c.children.forEach(v=>{
                                            if(v.materialId === row.materialId) {
                                                v.purchasingUnitId = item.orgId
                                                v.purchasingUnitName = item.orgName
                                                v.changeType = 2
                                            }
                                        })
                                    })
                                }else{
                                    row.changeType = 1
                                    this.OrgSonTableData.forEach(c=>{
                                        c.children.forEach(v=>{
                                            if(v.materialId === row.materialId) {
                                                v.purchasingUnitId = item.orgId
                                                v.purchasingUnitName = item.orgName
                                                v.changeType = 1
                                            }
                                        })
                                    })
                                }
                            })
                        })

                    })

                })

        },
        //获取承建单位
        getContractorName (orgId) {
            this.$Ajax
                .httpGet({
                    url: '/hr/org/getContractorOrg',
                    params: {
                        orgId: orgId,
                    },
                })
                // .then(res=>{
                //     console.log('承建单位', res)
                //     this.OrgtableData.forEach(a=>{
                //         a.children.forEach(b=>{
                //             b.children.forEach(c=>{
                //                 c.contractorId = res.orgId
                //                 c.contractorName = res.orgName
                //             })
                //         })
                //     })

            // })
        },
        isdata () {
            //判断如果子列表有数据就默认显示
            setTimeout(()=>{
                this.OrgtableData.forEach(item=>{
                    if(item.children != null) {
                        this.show = true
                    }else{
                        this.show = false
                    }
                })

            }, 500)
        },
        blur () {
            this.amount()
        },
        //汇总基础信息的计划金额
        amount () {
            let num = 0
            // 汇总所选择申报机构对应清单的人民币金额。保留两位小数  明细里的 金额（元)  {核准数量authorizedQuantity*核准单价authorizedPrice}

            this.OrgtableData.forEach(item=>{
                if(item.children != null) {
                    item.children.forEach(a=>{
                        a.children.forEach(b=>{
                            if(b.changeType != -1) {
                                num += b.authorizedQuantity * b.authorizedPrice
                            }
                        })
                    })
                    item.amount  = num
                    item.amount = item.amount.toFixed(2)

                }
            })
            for(let i = 0;i < this.OrgtableData.length;i++) {
                this.basicFormData.amount =  this.OrgtableData[i].amount
                this.basicFormData.amount  = this.basicFormData.amount.toFixed(2)
            }

        },
        //汇总申报机构明细 金额（元）
        AllbudgetAmount () {
            this.OrgSonTableData.forEach(a=>{
                a.children.forEach(c=>{
                    if(c.changeType != -1) {
                        c.amount = c.authorizedQuantity * c.authorizedPrice
                        c.amount = c.amount.toFixed(2)
                    }
                    this.materialsTableData.forEach(v=>{
                        v.children.forEach(o=>{
                            if(o.changeType != -1) {
                                if(o.materialId == c.materialId) {
                                    o.amount = c.amount
                                }
                            }
                        })
                    })
                })
            })
        },
        //保存
        save () {
            this.errorList = []
            Promise.all([this.updateBaseInfo(), this.updateBudgetDtl()])
                .then(() => {
                    this.clientPop('suc', '保存成功', this.$router.go(0) )//this.$router.go(0)
                })
                .catch(() => {
                    this.scorllError()
                })
        },
        //保存并提交
        submit () {
            this.errorList = []
            Promise.all([this.updateBaseInfo(), this.updateBudgetDtl()])
                .then(() => {
                    CommonApi.AuditCommit(this.auditParams).then(() => {
                        this.clientPop('suc', '保存并提交成功', this.handleClose, null, this.handleClose)
                    })
                })
                .catch(() => {
                    this.scorllError()

                })

        },
        //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject) => {
                this.$refs.ruleForm.validate(valid => {
                    if (valid) {

                        Api.EditPurchaseCollectBasic(this.basicFormData)
                            .then(() => {
                                this.getBasicData() //更新基本信息
                                resolve()
                            })
                            .catch(err => {
                                this.setError('baseInfo')
                                reject(err)
                            })
                    } else {
                        this.setError('baseInfo')
                        this.scorllError()
                        return false
                    }
                })
            })
        },
        //更新计划明细
        updateBudgetDtl () {
            return new Promise((resolve, reject) => {
                this.verifyTable()
                    .then(() => {
                        this.mergeData()
                        this.delchangeType()
                        this.isChangeType()
                        this.isprocurementMethod()
                        const p2 = Api.updateOrgDetails(this.OrgtableData)
                        //修改物资设置明细信息
                        console.log('this.materialsTableData', this.materialsTableData)
                        const p3 = Api.updateSettingList(this.materialsTableData)
                        Promise.all([ p2, p3])
                            .then(() => {
                                resolve()
                            })
                            .catch(err => {
                                this.setError('planDetail')
                                reject(err)
                            })
                    })
                    .catch(err => {
                        this.setError('planDetail')
                        reject(err)
                    })
            })
        },
        //明细非空验证
        verifyTable () {
            return new Promise((resolve, reject) => {
                this.errorMsg = []
                this.OrgtableData.forEach(c=>{
                    if(c.changeType != -1) {
                        if (this.OrgSonTableData.length > 0) {
                            this.OrgSonTableData.forEach(v => {
                                v.children.forEach((item, index) => {
                                    if (item.changeType !== -1) {
                                        if (item.authorizedQuantity === '' || item.authorizedQuantity === null) {
                                            let str = `请填写第 ${index + 1} 行的核准数量`
                                            this.errorMsg.push(str)
                                        }
                                        if (item.authorizedPrice === '' || item.authorizedPrice === null) {
                                            let str = `请填写第 ${index + 1} 行的核准单价`
                                            this.errorMsg.push(str)
                                        }
                                        if (item.purchasingUnitName === '' || item.purchasingUnitName === null || item.purchasingUnitName == undefined) {
                                            let str = `请选择第 ${index + 1} 行的集中采购单位`
                                            this.errorMsg.push(str)
                                        }
                                        if (item.procurementMethod === '' || item.procurementMethod === null || item.procurementMethod == undefined ) {
                                            let str = `请选择第 ${index + 1} 行的采购方式`
                                            this.errorMsg.push(str)
                                        }
                                    }
                                })
                            })
                        }

                        if (this.materialsTableData.length > 0) {
                            this.materialsTableData.forEach(v => {
                                v.children.forEach(item => {
                                    if (item.changeType !== -1) {
                                        // if (item.purchasingUnitName === '' || item.purchasingUnitName === null) {
                                        //     let str = `请选择第 ${index + 1} 行的集中采购单位`
                                        //     this.errorMsg.push(str)
                                        // }
                                        // if (item.procurementMethod === '' || item.procurementMethod === null) {
                                        //     let str = `请选择第 ${index + 1} 行的采购方式`
                                        //     this.errorMsg.push(str)
                                        // }
                                    }
                                })
                            })
                        }
                    }
                })

                if (this.errorMsg.length > 0) {
                    this.isErrorMsg = true
                    reject()
                } else {
                    this.isErrorMsg = false
                    resolve()
                }
            })
        },
        //设置错误标签
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        //保存时判断所有的changetype
        isChangeType () {
            this.OrgtableData.forEach(item=>{
                if(item.children != null) {
                    item.children.forEach(a=>{
                        a.children.forEach(b=>{
                            if(b.children === 2) {
                                item.changeType = 2
                            }
                        })
                    })

                }
            })
        },
        //把子列表的数据合并到this.OrgtableData的children
        mergeData () {
            this.OrgtableData.forEach(item=>{
                console.log('item', item)
                if( item.changeType == null || item.changeType == 0) {
                    item.changeType = 2
                    item.children = this.OrgSonTableData

                }else if(item.changeType == 1) {
                    item.changeType = 1
                    item.children = this.OrgSonTableData
                }else if(item.changeType == -1) {
                    item.changeType = -1
                    item.children = this.OrgSonTableData
                }

            })

        },

        //点击选择 选择申报单位 按钮选择明细

        selectUnit () {
            let ids = []
            selectDataClient({
                SelectServiceToken: '/material/masterPlan/queryPageForSelect', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: JSON.stringify({
                    'purchaseTypes': [1], //采购方式
                    'states': [] //单据状态
                },),
                Title: '选择集中采购的机构' // 标题
            }).then(val => {
                this.setSelectedInfo(val)
                //     openAppClient('/showSelectedData', '选择结果', function () {
                //         // alert('关闭后回调')
                //     })
                // let val = [{ 'billId': '1569507181187493889', 'billNo': 'SRBGEHGSL204CLZJH20220913001', 'amount': 132599.5, 'changedState': null, 'orgName': '四川公路桥梁建设集团有限公司峨眉至汉源高速公路2标段施工总承包项目4分部', 'planDate': '2022-09-22', 'purchaseType': 1, 'state': '2' }]
                if(this.OrgtableData.length > 0) {
                    console.log('this.OrgtableData????', this.OrgtableData)
                    this.OrgtableData.forEach(item=>{
                        console.log('item', item)
                        val.forEach(b=>{
                            console.log('val', b)
                            if(b.billId == item.masterPlanBillId) {
                                this.clientPop('err', '不能重复选择总计划!',)
                            }else{
                                let obj = {
                                    'amount': b.amount,  //金额(元)
                                    'billId': this.billid,   //集采汇总id
                                    'changeType': 1,
                                    'dtlId': '',    //汇总机构明细id
                                    'masterPlanBillId': b.billId,  //总计划id
                                    'masterPlanBillNo': b.billNo,  //总计划编号
                                    'orgId': this.orgId,
                                    'orgName': b.orgName,
                                    'children': [],
                                }
                                this.OrgtableData.push(obj)
                                this.basicFormData.amount = b.amount
                                this.billIdArr.push(b.billId)
                                this.materialsTableDataAarry()
                                this.billIdArr = []
                                this.AllbudgetAmount()
                                this.amount()

                            }

                        })

                    })

                }else{
                    val.forEach(b=>{
                        let obj = {
                            'amount': b.amount,  //金额(元)
                            'billId': this.billid,   //集采汇总id
                            'changeType': 1,
                            'dtlId': '',    //汇总机构明细id
                            'masterPlanBillId': b.billId,  //总计划id
                            'masterPlanBillNo': b.billNo,  //总计划编号
                            'orgId': this.orgId,
                            'orgName': b.orgName,
                            'children': [],
                        }
                        this.OrgtableData.push(obj)
                        this.basicFormData.amount = b.amount
                        this.billIdArr.push(b.billId)

                    })
                    this.materialsTableDataAarry()
                    this.billIdArr = []
                    this.AllbudgetAmount()
                    this.amount()
                }
                // if(this.OrgtableData.length > 0) {
                //     val.forEach(a=>{
                //         this.OrgtableData.forEach(item=>{
                //             if(a.billId === item.masterPlanBillId) {
                //                 this.clientPop('err', '不能重复选择总计划!',)
                //                 this.OrgtableData.pop()
                //                 val.forEach(item=>{
                //                     let obj = {
                //                         'amount': item.amount,  //金额(元)
                //                         'billId': this.billid,   //集采汇总id
                //                         'changeType': 1,
                //                         'dtlId': '',    //汇总机构明细id
                //                         'masterPlanBillId': item.billId,  //总计划id
                //                         'masterPlanBillNo': item.billNo,  //总计划编号
                //                         'orgId': this.orgId,
                //                         'orgName': item.orgName,
                //                         'children': [],
                //                     }
                //                     this.OrgtableData.push(obj)
                //                     this.basicFormData.amount = item.amount
                //                     this.billIdArr.push(item.billId)
                //                 })
                //                 if(val) {
                //                     this.materialsTableDataAarry()
                //                     this.billIdArr = []
                //                     this.AllbudgetAmount()
                //                     this.amount()
                //                 }
                //             }
                //         })
                //     })
                // }else{

            //     //this.OrgtableData = this.OrgtableData ? this.OrgtableData : []
            //     val.forEach(item=>{
            //         let obj = {
            //             'amount': item.amount,  //金额(元)
            //             'billId': this.billid,   //集采汇总id
            //             'changeType': 1,
            //             'dtlId': '',    //汇总机构明细id
            //             'masterPlanBillId': item.billId,  //总计划id
            //             'masterPlanBillNo': item.billNo,  //总计划编号
            //             'orgId': this.orgId,
            //             'orgName': item.orgName,
            //             'children': [],
            //         }
            //         this.OrgtableData.push(obj)
            //         this.basicFormData.amount = item.amount
            //         this.billIdArr.push(item.billId)
            //     })
            //     if(val) {
            //         this.materialsTableDataAarry()
            //         this.billIdArr = []
            //         this.AllbudgetAmount()
            //         this.amount()
            //     }
            // }
            })

        },

        //选择计划明细
        selectPlans () {
            let ids = []
            selectDataClient({
                SelectServiceToken: '/material/masterPlan/getListByIdForSelect', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: JSON.stringify({
                    id: this.masterPlanBillId,
                },),    // 接口参数(name为模拟参数)
                Title: '选择明细' // 标题
            }).then(val=>{
                this.setSelectedInfo(val)
                val.forEach(e=>{
                    e.uuid = getUuid()
                    e.customId = getUuid(),
                    e.changeType = 1
                    e.billId = this.billid
                    e.materialClassNameArr = e.materialClassName.split('/')
                    e.materialClassIdArr = e.materialClassId.split('/')
                    e.materialClassId = e.materialClassIdArr.splice(0, 1).toString()
                    e.materialClassName = e.materialClassNameArr.splice(0, 1).toString()
                    e.materialClassId = e.materialClassIdArr.join('/')
                    e.materialClassName = e.materialClassNameArr.join('/')
                    this.OrgSonTableData.forEach(item=>{
                        item.children.unshift(e)
                    })

                })
                this.setSelectedInfo(val)
            })
        },
        //点击申报单位列表点击编号显示对应子列表    23232
        async showTable (row) {
            console.log('OrgtableData', this.OrgtableData)
            console.log('row', row)
            this.OrgSonTableData = []
            this.getContractorName(row.orgId)  //'a94220dc34ae-a5b7-bb41-a2a1-b590b187'

            this.masterPlanBillId = row.masterPlanBillId
            this.OrgtableData.forEach(a=>{
                if(a.orgId == row.orgId) {
                    row.children.forEach(a=>{
                        this.OrgSonTableData.push(a)
                        this.OrgSonTableData = [
                            {
                                topClassId: '',
                                topClassName: '',
                                totalAmount: '',
                                totalQuantity: '',
                                materialClassId: '',
                                materialClassName: '',
                                uuid: '',
                                children: [],
                                changeType: 1,
                                dtlId: '',
                            }
                        ]
                        const mapObj = {}
                        let arr = []
                        a.children.forEach(e=>{
                            const children = []
                            let obj
                            const topClassId = a.topClassId
                            const topClassName = a.topClassName
                            if (!mapObj[topClassId]) {
                                obj = {
                                    topClassId,
                                    topClassName,
                                    customId: topClassId,
                                    materialClassId: topClassId,
                                    materialClassName: topClassName,
                                    uuid: getUuid(),
                                    totalAmount: '',
                                    totalQuantity: '',
                                }
                                //这里需要改成push多个对象   还没改
                                arr.push(obj)

                                mapObj[topClassId] = obj
                            } else {
                                obj = mapObj[topClassId]
                            }
                            //  物资名称
                            children.push({
                                uuid: getUuid(),
                                customId: getUuid(),
                                masterPlanBillId: e.masterPlanBillId,
                                'amount': e.amount, //金额(元)
                                'authorizedPrice': e.authorizedPrice, //核准单价(元)
                                'authorizedQuantity': e.authorizedQuantity, //核准数量
                                'billId': this.billid, //集采汇总id
                                'changeType': 1, //
                                'contractorId': '', //承建单位id
                                'contractorName': '', //承建单位名称
                                'dtlId': e.dtlId, //物资汇总明细id
                                'marketPrice': e.marketPrice, //市场单价(元)
                                'masterPlanDtlId': e.masterPlanDtlId, //总计划明细id
                                'materialClassId': e.materialClassId, //物资类别id
                                'materialClassName': e.materialClassName, //物资类别名称
                                'materialId': e.materialId, //物资id
                                'materialName': e.materialName, //物资名称
                                'planQuantity': e.planQuantity, //计划数量
                                'procurementMethod': e.procurementMethod, //采购方式
                                'purchasingUnitId': e.purchasingUnitId, //集中采购单位id
                                'purchasingUnitName': e.purchasingUnitName, //集中采购单位名称
                                'remarks': e.remarks, //备注
                                'reportingAgencyDtlId': e.reportingAgencyDtlId, //申报机构明细id
                                'spec': e.spec, //规格型号
                                'texture': e.texture, //材质
                                'unit': e.unit //计量单位

                            })
                            obj.children = !obj.children
                                ? children
                                : obj.children.concat(children)
                            // 统计小计
                            const count = obj.children.reduce(
                                (prev, c) => (prev += c.amount || 0),
                                0
                            )
                            obj.materialName = `小计： ${count}`
                            obj.children = this.uniqueArray(obj.children, 'customId')

                        })
                        this.OrgSonTableData = arr
                        console.log('this.OrgSonTableData', this.OrgSonTableData)
                        // this.AllbudgetAmount()
                        // this.amount()

                    })

                }
            })

        },
        count_ (obj) {
            return obj.children.reduce((prev, c) => (prev += c.amount || 0), 0)
        },
        //明细数据汇总方法
        uniqueArray (arr, key) {
            const map = new Map()
            return arr.filter(item => {
                const val = item[key] + '' || getUuid()
                return !map.has(val) && map.set(val, 1)
            })
        },
        //申报机构汇总-删除 申报机构汇总表格明细
        deleteMaterials () {
            this.planSelect.forEach((item, index) => {
                if (item.dtlId) {
                    item.changeType = -1
                    this.basicFormData.amount = 0
                } else {
                    this.OrgtableData.splice(index, this.planSelect.length)
                    console.log('删除后this.OrgtableData', this.OrgtableData)
                }
            })
        },

        //监听明细 机构汇总表格 数据input事件 判断用户是否修改
        input (row) {
            console.log('row', row)
            if(row.authorizedQuantity > row.planQuantity) {
                this.clientPop(
                    'err',
                    '核准数量不能超过计划数量!',
                )
                setTimeout(()=>{
                    row.authorizedQuantity = row.planQuantity

                })

            }
            this.OrgtableData.forEach(a=>{
                a.children.forEach(b=>{
                    b.children.forEach(c=>{
                        console.log('c', c)
                        if(row.dtlId) {
                            if(row.materialId == c.materialId) {
                                a.changeType = 2
                                c.changeType = 2
                                c.authorizedPrice = row.authorizedPrice
                                c.authorizedQuantity = row.authorizedQuantity
                            }

                        }else{
                            if(row.materialId == c.materialId) {
                                c.authorizedPrice = row.authorizedPrice
                                c.authorizedQuantity = row.authorizedQuantity
                            }
                        }
                    })
                })
            })
            console.log('this.OrgtableData', this.OrgtableData)

        },

        //选择申报机构汇总采购方式，修改状态
        selectProcurementMethod (row) {
            this.OrgtableData.forEach(a=>{
                a.children.forEach(b=>{
                    b.children.forEach(c=>{
                        this.materialsTableData.forEach(k=>{
                            k.children.forEach(v=>{
                                if(a.changeType == 2 || a.changeType == null || a.changeType == 0) {
                                    if(c.materialId == row.materialId) {
                                        a.changeType = 2
                                        c.changeType = 2
                                        c.procurementMethod = row.procurementMethod
                                    }
                                    if(row.materialId == v.materialId) {
                                        k.changeType = 2
                                        v.changeType = 2
                                        v.procurementMethod = row.procurementMethod
                                    }

                                }else if(a.changeType == 1) {
                                    if(c.materialId == row.materialId) {
                                        a.changeType = 1
                                        c.changeType = 1
                                        c.procurementMethod = row.procurementMethod
                                    }
                                    if(row.materialId == v.materialId) {
                                        k.changeType = 1
                                        v.changeType = 1
                                        v.procurementMethod = row.procurementMethod
                                    }
                                }

                            })
                        })

                    })
                })
            })

        },
        //选择物资汇总的采购方式
        selectProcurementMethodTwo (row) {
            if(row.changeType === 1) {
                row.changeType = 1
            }else{
                row.changeType = 2
            }

            this.OrgSonTableData.forEach(item=>{
                item.children.forEach(a=>{
                    console.log('a', a)
                    if(a.dtlId) {
                        if(row.materialId == a.materialId) {
                            a.changeType = 2
                            a.procurementMethod = row.procurementMethod
                        }
                    }else{
                        if(row.materialId == a.materialId) {
                            a.changeType = 1
                            a.procurementMethod = row.procurementMethod
                        }
                    }

                })

            })
        },
        //根据总计划billid集合获取总计划明细集合
        async  materialsTableDataAarry () {
            Api.getListByIds(this.billIdArr).then(res=>{
                this.OrgtableData.forEach(a=>{
                    res.forEach(b=>{
                        if(a.masterPlanBillId === b.billId ) {
                            const obj = {
                                billId: b.billId,
                                children: [],
                                topClassId: b.topClassId,
                                topClassName: b.topClassName,
                                totalAmount: b.totalAmount,
                                totalQuantity: b.totalQuantity,
                            }
                            b.children.forEach(c=>{
                                const obj2 = {
                                    uuid: getUuid(),
                                    customId: getUuid(),
                                    masterPlanBillId: c.billId,
                                    masterPlanBillNo: c.billNo,
                                    'amount': c.marketAmount,   //金额(元)
                                    'authorizedPrice': c.marketPrice,  //核准单价(元)
                                    'authorizedQuantity': c.planQuantity, //核准数量
                                    'billId': this.billid, //集采汇总id
                                    'changeType': 1,
                                    'contractorId': '', //承建单位id
                                    'contractorName': '', //承建单位名称
                                    'dtlId': '', //物资汇总明细id
                                    'marketPrice': c.marketPrice, //市场单价(元)
                                    'masterPlanDtlId': c.dtlId, //总计划明细id
                                    'materialClassId': c.materialClassId, //物资类别id
                                    'materialClassName': c.materialClassName, //物资类别名称
                                    'materialId': c.materialId, //物资id
                                    'materialName': c.materialName, //物资名称
                                    'planQuantity': c.planQuantity, //计划数量
                                    'procurementMethod': c.procurementMethod, //采购方式
                                    'purchasingUnitId': c.purchasingUnitId, //集中采购单位id
                                    'purchasingUnitName': c.purchasingUnitName, //集中采购单位id
                                    'remarks': '', //备注
                                    'reportingAgencyDtlId': '', //申报机构明细id
                                    'spec': c.spec, //规格型号
                                    'texture': c.texture, //材质
                                    'unit': c.unit, //计量单位
                                    'planPrice': '', //	计划单价(元)

                                }
                                obj.children.push(obj2)
                            })
                            a.children.push(obj)
                            this.getContractorName(a.orgId)

                            this.OrgSonTableData = [
                                {
                                    topClassId: '',
                                    topClassName: '',
                                    totalAmount: '',
                                    totalQuantity: '',
                                    materialClassId: '',
                                    materialClassName: '',
                                    uuid: '',
                                    children: [],
                                    changeType: 1,
                                    dtlId: '',
                                }
                            ]
                            this.$Ajax
                                .httpGet({
                                    url: '/material/masterPlan/getListByIdForSelect',
                                    params: {
                                        id: a.masterPlanBillId,
                                    },
                                    headers: {
                                        'Content-Type': 'application/x-www-form-urlencoded',
                                    },
                                })
                                .then(res => {
                                    console.log('res', res)
                                    const mapObj = {}
                                    let arr = []
                                    res.forEach(e => {
                                        const children = []
                                        e.materialClassNameArr = e.materialClassName.split('/')
                                        e.materialClassIdArr = e.materialClassId.split('/')
                                        // TODO: 统计小计
                                        let obj
                                        const topClassId = e.materialClassIdArr.splice(0, 1).toString()
                                        const topClassName = e.materialClassNameArr.splice(0, 1).toString()
                                        if (!mapObj[topClassId]) {
                                            obj = {
                                                topClassId,
                                                topClassName,
                                                customId: topClassId,
                                                materialClassId: topClassId,
                                                materialClassName: topClassName,
                                                uuid: getUuid(),
                                                totalAmount: '',
                                                totalQuantity: '',
                                            }
                                            //这里需要改成push多个对象   还没改
                                            arr.push(obj)

                                            mapObj[topClassId] = obj
                                        } else {
                                            obj = mapObj[topClassId]
                                        }

                                        // 物资名称
                                        children.push({
                                            uuid: getUuid(),
                                            customId: getUuid(),
                                            masterPlanBillId: e.billId,
                                            'amount': e.marketAmount, //金额(元)
                                            'authorizedPrice': e.marketPrice, //核准单价(元)
                                            'authorizedQuantity': e.unsummarizedQuantity, //核准数量
                                            'billId': this.billid, //集采汇总id
                                            'changeType': 1, //
                                            'contractorId': '', //承建单位id
                                            'contractorName': '', //承建单位名称
                                            'dtlId': '', //物资汇总明细id
                                            'marketPrice': e.marketPrice, //市场单价(元)
                                            'masterPlanDtlId': e.dtlId, //总计划明细id
                                            'materialClassId': e.materialClassIdArr.join('/'), //物资类别id
                                            'materialClassName': e.materialClassNameArr.join('/'), //物资类别名称
                                            'materialId': e.materialId, //物资id
                                            'materialName': e.materialName, //物资名称
                                            'planQuantity': e.planQuantity, //计划数量
                                            'procurementMethod': e.procurementMethod, //采购方式
                                            'purchasingUnitId': e.purchasingUnitId, //集中采购单位id
                                            'purchasingUnitName': e.purchasingUnitName, //集中采购单位名称
                                            'remarks': '', //备注
                                            'reportingAgencyDtlId': '', //申报机构明细id
                                            'spec': e.spec, //规格型号
                                            'texture': e.texture, //材质
                                            'unit': e.unit //计量单位

                                        })
                                        obj.children = !obj.children
                                            ? children
                                            : obj.children.concat(children)
                                        // 统计小计
                                        const count = obj.children.reduce(
                                            (prev, c) => (prev += c.amount || 0),
                                            0
                                        )
                                        obj.materialName = `小计： ${count}`
                                        obj.children = this.uniqueArray(obj.children, 'customId')
                                    })
                                    this.OrgSonTableData = arr
                                    this.AllbudgetAmount()
                                    this.amount()

                                })

                        }
                    })
                })

                //去重
                let children = []
                res.forEach(item=>{
                    item.children.forEach(a=>{
                        children.push(a)
                    })
                })
                var result = []
                var obj = {}
                for (var i = 0; i < children.length; i++) {
                    if ( children[i].materialId in obj) {
                    // 相同时肯定不push
                        if (obj[children[i].materialId] !== children[i].texture) {
                        // 不相同时，判断是否是 '' 和 null，如果是，则表示重复
                            if (!(!obj[children[i].materialId] && !children[i].texture)) {
                            // 当都不是 '' 和 null 时，才表示不重复，此时才push
                                result.push(children[i])
                            }
                        }
                    } else {
                        obj[children[i].materialId] = children[i].texture
                        result.push(children[i])
                    }
                }
                //给物资汇总列表赋值

                this.materialsTableData = []

                res.forEach(item=>{

                    this.OrgAllData.push(item)
                    this.materialsTableData = [
                        {

                            topClassId: '',
                            topClassName: '',
                            materialClassId: '',
                            materialClassName: '',
                            uuid: '',
                            totalAmount: '',
                            totalQuantity: '',
                            children: []
                        }
                    ]
                    //一级赋值
                    this.materialsTableData.forEach(a=>{
                        a.topClassId = item.topClassId
                        a.topClassName = item.topClassName
                        a. materialClassId = item.materialClassId
                        a.materialClassName = item.topClassName
                        a.totalAmount = item.totalAmount
                        a.totalQuantity = item.totalQuantity
                        a.uuid = getUuid()
                        result.forEach(b=>{
                            const obj = {
                                uuid: getUuid(),
                                // billId: this.billid,
                                // changeType: 1,
                                // designQuantity: b.designQuantity,
                                // dtlId: b.dtlId,
                                // marketAmount: b.marketAmount,
                                // marketPrice: b.marketPrice,
                                // materialClassId: b.materialClassId,
                                // materialClassName: b.materialClassName,
                                // materialId: b.materialId,
                                // materialName: b.materialName,
                                // planQuantity: b.planQuantity,
                                // projectPlanDtlId: b.projectPlanDtlId,
                                // procurementMethod: b.procurementMethod,
                                // purchasingUnitId: b.purchasingUnitId,
                                // purchasingUnitName: b.purchasingUnitName,
                                // spec: b.spec,
                                // texture: b.texture,
                                // unit: b.unit,
                                // 'amount': b.budgetAmount,
                                // 'planPrice': 0,
                                'amount': b.marketAmount,
                                'billId': this.billid,
                                'changeType': 1,
                                'dtlId': b.dtlId,
                                'marketPrice': b.marketPrice,
                                'materialClassId': b.materialClassId,
                                'materialClassName': b.materialClassName,
                                'materialId': b.materialId,
                                'materialName': b.materialName,
                                'planPrice': 0,
                                'planQuantity': b.planQuantity,
                                'procurementMethod': b.purchaseType,
                                'purchasingUnitId': b.purchasingUnitId,
                                'purchasingUnitName': b.purchasingUnitName,
                                'spec': b.spec,
                                'texture': b.texture,
                                'unit': b.unit

                            }
                            a.children.push(obj)
                        })
                    })
                })
            })
        },
        //根据集采汇总id获取物资汇总明细信息
        getSettingListById () {
            this.$Ajax
                .httpGet({
                    url: '/material/centralizedPurchaseSummary/getSettingListById',
                    params: {
                        id: this.billid,
                    },
                })
                .then(res => {
                    console.log('物资汇总', res)
                    res.forEach(item => {
                        item.materialClassName = item.topClassName
                        item.uuid = getUuid()
                        item.children.forEach(i => {
                            i.uuid = i.dtlId
                        })
                        // const count = item.children.reduce(
                        //     (prev, c) => (prev += c.amount || 0),
                        //     0
                        // )
                        // item.materialName = `小计： ${count}`
                    })
                    this.materialsTableData = res

                })
        },

        //修改物资汇总的删除状态
        delchangeType () {
            this.OrgtableData.forEach(item=>{
                if(item.changeType === -1) {
                    this.materialsTableData.forEach(a=>{
                        a.children.forEach(b=>{
                            b.changeType = -1
                            console.log(b.changeType)
                        })

                    })
                }
                else if(item.changeType === 2) {
                    this.materialsTableData.forEach(a=>{
                        a.children.forEach(b=>{
                            if(b.changeType == -1) {
                                b.changeType = -1
                            }else if(b.changeType == 2) {
                                b.changeType = 2
                            }
                            else{
                                b.changeType = 0
                            }
                        })
                    })
                }
            })

        },
        //点击物资汇总的物资名称，汇总物资下的所有机构
        showA (row) {
            this.showTwo = true

            this.OrgtableData.forEach(item=>{
                console.log(item)
                item.children.forEach(a=>{
                    a.children.forEach(b=>{
                        if( row.materialId === b.materialId) {
                            const obj = {
                                orgName: item.orgName,
                                materialName: b.materialName,
                                spec: b.spec,
                                unit: b.unit,
                                texture: b.texture,
                                planQuantity: b.planQuantity,
                                marketPrice: '',
                                amount: b.amount
                            }
                            this.materialsNameData = []
                            this.materialsNameData.push(obj)
                        }
                    })
                })

            })

        },
        //获取集采汇总id获取基本信息
        getBasicData () {
            this.$Ajax
                .httpGet({
                    url: '/material/centralizedPurchaseSummary/findById',
                    params: {
                        id: this.billid,
                    },
                })
                .then(res => {

                    this.basicFormData = res

                })
        },
        //根据集采汇总id获取申报机构明细信息
        getMasterPurchase () {
            this.$Ajax
                .httpGet({
                    url: '/material/centralizedPurchaseSummary/getReportingAgencyListById',
                    params: {
                        id: this.billid,
                    },
                })
                .then(res => {
                    console.log('res', res)
                    if(res.length > 1) {
                        res.pop()
                    }
                    res.forEach(item => {
                        this.masterPlanBillId = item.masterPlanBillId
                        this.OrgtableData.push(item)
                        if(item.children == null) {
                            return
                        }else{
                            item.children.forEach(i=>{

                                this.OrgSonTableData = [
                                    {
                                        topClassId: '',
                                        topClassName: '',
                                        totalAmount: '',
                                        totalQuantity: '',
                                        materialClassId: '',
                                        materialClassName: '',
                                        uuid: '',
                                        children: [],
                                        changeType: 1,
                                    }
                                ]
                                this.OrgSonTableData.forEach(e=>{
                                    e.topClassId = i.topClassId
                                    e.topClassName = i.topClassName
                                    e.totalAmount = i.totalAmount
                                    e.totalQuantity = i.totalQuantity
                                    e.materialClassId = i.topClassId
                                    e.materialClassName = i.topClassName
                                    e.uuid = getUuid()
                                    i.children.forEach(o=>{
                                        const obj = {
                                            uuid: getUuid(),
                                            masterPlanBillId: '',
                                            masterPlanBillNo: '',
                                            'amount': o.amount,   //金额(元)
                                            'authorizedPrice': o.authorizedPrice,  //核准单价(元)
                                            'authorizedQuantity': o.authorizedQuantity, //核准数量
                                            'billId': o.billId, //集采汇总id
                                            'changeType': null,
                                            'contractorId': o.contractorId, //承建单位id
                                            'contractorName': o.contractorName, //承建单位名称
                                            'dtlId': o.dtlId, //物资汇总明细id
                                            'marketPrice': o.marketPrice, //市场单价(元)
                                            'masterPlanDtlId': o.masterPlanDtlId, //总计划明细id
                                            'materialClassId': o.materialClassId, //物资类别id
                                            'materialClassName': o.materialClassName, //物资类别名称
                                            'materialId': o.materialId, //物资id
                                            'materialName': o.materialName, //物资名称
                                            'planQuantity': o.planQuantity, //计划数量
                                            'procurementMethod': o.procurementMethod, //采购方式
                                            'purchasingUnitId': o.purchasingUnitId, //集中采购单位id
                                            'purchasingUnitName': o.purchasingUnitName, //集中采购单位id
                                            'remarks': o.remarks, //备注
                                            'reportingAgencyDtlId': o.reportingAgencyDtlId, //申报机构明细id
                                            'spec': o.spec, //规格型号
                                            'texture': o.texture, //材质
                                            'unit': o.unit //计量单位
                                        }
                                        e.children.push(obj)
                                    })
                                })

                            })

                        }

                    })

                })
        },
        //撤回
        undoAudit () {
            const params2 = {
                billId: this.billid, //单据Id  ***
                billType: '1004', //单据编码  ***
                dtls: [], //审核中字段值变更历史
                freeNextUnitIndex: 0, //下一步审核步骤
                freeNextUser: '', //下一步审核人ID
                isPass: true, //审核是否通过
                isShareInAudit: true, //是否共享审核节点
                opinion: '', //审核意见   ***
                orgId: '', //单据机构Id
                orgName: '', //单据机构名称
                userId: this.userId, //审核人Id    ***
                workId: '', //流程Id
            }
            CommonApi.undoAudit(params2).then(() => {
                this.clientPop('suc', '撤回成功！', this.handleClose, null, this.handleClose)
            })
        },
        //获取历史审核列表
        getAuditHistory () {
            const params = {
                billId: this.billid,
                billType: '1004',
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: '',
                orgId: '',
                orgName: '',
                userId: '',
                workId: ''
            }
            CommonApi.getAuditHistory(params).then(res => {
                this.auditHistoryTable = res
            })
        },

        //删除提示框
        ctDelete () {
            this.clientPop(
                'info',
                '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。',
                this.delData
            )
        },
        //根据集采汇总id删除单据
        delData () {
            this.$Ajax
                .httpGet({
                    url: '/material/centralizedPurchaseSummary/delete',
                    params: {
                        id: this.billid,
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                })
                .then(res => {
                    if (res.code == 200) {
                        this.clientPop('suc', '删除成功', this.handleClose, null, this.handleClose)
                    }
                })
        },
        handleFullScreen () {
            this.fullscreen = !this.fullscreen
        },
        //查询附件信息
        getAttach () {
            this.objFlag.flag5 = true
        },
        ...mapMutations(['setPopConfirm']),
        //申报机构汇总-明细子列表删除按钮
        deleteEle (row) {
            row.changeType = -1
            console.log('row.changeType', row)
            this.OrgtableData.forEach(item =>{
                item.children.forEach(v=>{
                    v.children.forEach((i, index)=>{
                        console.log('i', i)
                        if(i.dtlId) {
                            item.changeType = 2
                            if(i.materialId === row.materialId) {
                                i.changeType = -1
                            }
                        }else{
                            if(i.materialId === row.materialId) {
                                v.children.splice(index, 1)
                            }
                        }

                    })
                })

            })
            this.materialsTableData.forEach(item=>{
                item.children.forEach(a=>{
                    if(row.materialId ===  a.materialId) {
                        a.changeType = -1
                    }
                })
            })
            this.amount()
            this.AllbudgetAmount()
        },
        //申报机构删除逻辑
        tableRowClassName ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },
        //申报机构子列表删除逻辑
        tableRowClassNames ({ row }) {
            if(row.children) {
                return
            }else{
                if(row.changeType === -1) {
                    return 'warning-row'
                }
                return ''

            }
        },
        tableRowClassNamess ({ row }) {

            if(row.changeType === -1) {
                return 'warning-row'
            }
            return ''

        },
        //获取用户在 汇总明细-申报机构汇总 表格的已选择项
        planTableSelect (selection) {
            this.planSelect = selection
        },
        //取消
        handleClose () {
            this.dialogVisible = false
            this.$router.replace('./purchaseCollect')
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('evaluateCon')) {
                    const lastConHeight =
            document.getElementById('evaluateCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    console.log('this.lastConHeight', this.lastConHeight)
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.dtlId
        },
        cellMouseLeave () {
            this.AllbudgetAmount()   //鼠标离开表格计算
            this.MouseEnterId = 0
        },

    },
    computed: {
        ...mapState({
            options: state => state.contract.ctClassify,
        }),
        judgeRoute () {
            if (this.$route.path.includes('Add')) {
                return false
            }
            return true
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.billid
        },
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData => {
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM => {
                const { childNodes } = DOM
                if (childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item => {
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
    },
    components: {
        AttachComp,
        ComAuditHistoryIndex,
    },
    mounted () {
    // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = [
            'baseInfo',
            ['planDetail', 'materialDetails', 'technicalParameter'],
            'accessory',
            'auditHistory',
        ]
        this.tabArr = arr //标星星
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //当点击的tab有子tab时做滚动逻辑
            if (this.clickTabFlag && arr.find(x => x === this.clickId)) {
                this.childTabClass = '' //无子tab时清空tab的类名
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    let itemTop
                    let arr
                    if (item instanceof Array) {
                        const prevHeight = document.getElementById(item[0]).offsetHeight //因这里一个选项有两个表格，需获取前一个表格的高度进行计算
                        arr = item.map((x, i) => {
                            if (i === 0) {
                                return document.getElementById(x).offsetTop
                            } else {
                                return (
                                    document.getElementById(x).offsetTop +
                  prevHeight +
                  document.getElementById(item[0]).offsetTop
                                )
                            }
                        })
                        return arr
                    } else {
                        itemTop = document.getElementById(item).offsetTop
                        return itemTop
                    }
                })
            }
            const scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            let curLocalChild = 1
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                if ($idsTop[i] instanceof Array) {
                    let item = $idsTop[i]
                    for (let lenth = item.length, j = lenth - 1; j >= 1; j--) {
                        let itemChild = $idsTop[i][j]
                        if (scrollTop + 1 >= itemChild) {
                            curLocalChild = j
                            break
                        }
                    }
                    if (scrollTop + 1 >= item[0]) {
                        curLocal = i
                        break
                    }
                } else {
                    let item = $idsTop[i]
                    if (scrollTop + 1 >= item) {
                        curLocal = i
                        break
                    }
                }
            }
            // 设置对应tabName
            if (arr[curLocal] instanceof Array) {
                this.tabsName = arr[curLocal][0]
                this.tabsNameChild = arr[curLocal][curLocalChild]
            } else {
                this.tabsName = arr[curLocal]
            }
            //动态改变二级选项卡类名
            arr.forEach((item, index) => {
                if (item instanceof Array) {
                    let tabNavHeight = document.querySelector('.childTab .el-tabs__nav')
                        ? document.querySelector('.childTab .el-tabs__nav').offsetHeight
                        : 0
                    if (scrollTop + 1 >= $idsTop[index + 1] - tabNavHeight) {
                        this.childTabClass = 'childTab2'
                    } else if (scrollTop <= $idsTop[index][1]) {
                        this.childTabClass = ''
                    } else {
                        this.childTabClass = 'childTab1'
                    }
                }
            })
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                let itemTop
                let arr
                if (item instanceof Array) {
                    const prevHeight = document.getElementById(item[0]).offsetHeight //因这里一个选项有两个表格，需获取前一个表格的高度进行计算
                    arr = item.map((x, i) => {
                        if (i === 0) {
                            return document.getElementById(x).offsetTop
                        } else {
                            return (
                                document.getElementById(x).offsetTop +
                prevHeight +
                document.getElementById(item[0]).offsetTop
                            )
                        }
                    })
                    return arr
                } else {
                    itemTop = document.getElementById(item).offsetTop
                    return itemTop
                }
            })
        })
        this.scorllDtl()
    },
}
</script>

<style lang="scss" scoped>
.buttons {
  left: 0;
}
.e-form {
  margin-bottom: 80px;
  padding: 0 20px;
  .tabs-title::before {
    content: "";
    height: 22px;
    width: 8px;
    border-radius: 40px;
    background-color: #2e61d7;
    display: block;
    position: absolute;
    left: 20px;
    margin-right: 20px;
  }
}

.e-table {
  background: #fff;
}
::v-deep.el-table .warning-row {
  display: none;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  width: 6px; // 横向滚动条
  height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 5px;
}

.el-tab-pane {
  margin-left: -10px;
}
.childTab {
  ::v-deep .el-tabs__header {
    position: absolute !important;
  }
  ::v-deep .el-tabs__content {
    padding: 0 0 0 20px !important;
  }
}
.childTab1 {
  ::v-deep .el-tabs__header {
    position: absolute !important;
    .el-tabs__nav-scroll {
      position: relative;
      .el-tabs__nav {
        position: fixed;
        top: 0;
        width: 190px;
      }
    }
  }
}
.childTab2 {
  ::v-deep .el-tabs__header {
    position: absolute !important;
    .el-tabs__nav-scroll {
      position: relative;
      .el-tabs__nav {
        position: absolute;
        bottom: 0;
        width: 100%;
      }
    }
  }
}
</style>